#include <QSettings>
#include "clientcontroller.h"
#include "buddymodel.h"

ClientController::ClientController(QObject *parent) :
    QObject(parent)
{
 /*
    this->ctcdlg = NULL;

    // setup UI
    form = new Ui_MainWindow;
    form->setupUi(this);
    connect(form->actionConnect_to_Core, SIGNAL(activated()),
            this, SLOT(showConnectToCoreDialog()));
    connect(form->actionDisconnect_from_Core,SIGNAL(activated()),
            this, SLOT(disconnectCore()));
*/

    // init settings
    m_settings = new QSettings(
                                QSettings::IniFormat,
                                QSettings::UserScope,
                                QApplication::organizationDomain(),
                                QApplication::applicationName()
                              );

    // FIXME
    // This should be read from filesystem using QSettings
    QHash<QString,QVariant> t;
    t.insert("jid","dichat@betaworx.de");

    this->accData.insert(1,t);
/*
    // setup the main chat window
    this->mainChatWindow = new chatWindow(NULL);
    this->mainChatWindow->setDockNestingEnabled(false);
    this->show();
*/
}

/**
* @brief disconnect from the core
*/
void ClientController::disconnectCore()
{
    this->socket->close();

    // clear buddy list
    this->buddymodel = new BuddyModel();
    this->form->buddyView->setModel(this->buddymodel);

    // enable/disable menubuttons
    this->form->actionConnect_to_Core->setEnabled(true);
    this->form->actionDisconnect_from_Core->setEnabled(false);
}

/**
* @brief get a Buddy's name from the model
*
* the buddy is identified by its jid and the accid he is associated with
*/
QString SslClient::getBuddyName(int accID,QString jid)
{
    return this->buddymodel->getBuddyName(accID,jid);
}


/**
* @brief get the jid associated to an account by its id
* @returns jid
*/
QString SslClient::getJidByAccID(QVariant accid)
{
    QHash<QString,QVariant>  t = this->accData.value(accid.toInt());
    if (t.isEmpty())
    {
        qDebug() << "requested a jid for an accid that is unknown to the client";
        return "";
    }
    QString jid = t.value("jid","").toString();
    if (jid == "")
    {
        qDebug() << "strange. We know the accid, but have no jid associated to it";
    }
    return jid;
}

/**
* @brief open a chat with a buddy referenced by its index in the BuddyModel
*/
void SslClient::openChatWithBuddy(QModelIndex b)
{
    // Buddy? (we check die Icon-col) FIXME, maybe create a method isBuddy(QModelIndex) in BuddyModel
    if (this->buddymodel->index(b.row(),1,b.parent()).data(Qt::DisplayRole).toString() != "b")
        return;

    // Extract the buddy's information from the model
    QModelIndex buddyIndex = this->buddymodel->index(b.row(),0,b.parent());
    QString buddyName = buddyIndex.data(Qt::DisplayRole).toString();
    QString jid = this->buddymodel->index(b.row(),2,b.parent()).data(Qt::DisplayRole).toString();

    // open the chat widget (discard the returned pointer, we dont need)
   getChatWidget(1,jid,buddyName);

}

/**
* @brief send a message to the core
*
* encapsulate a message typed in the chatwidget into xml-schema and write it to the socket.
* the core then delegates this to the xmpp-server
* AND echoes it back to us with DateTime information. We dont display it back to the user
* until we get this echoed message.
*/
void SslClient::msgSend(int accid,QString jid,QString text)
{
    qDebug() << QString("requesting msg from acc %1 to jid %2, content: %3").arg(accid).arg(jid).arg(text);
    QString msg = QString("<xml><message><accid>%1</accid><to>%2</to><from>%3</from><content>%4</content></message>")
                  .arg(accid)
                  .arg(jid)
                  .arg(this->accData.value(accid).value("jid").toString())
                  .arg(text);
    this->socket->write(msg.toUtf8()+"\r\n");
}

/**
* @brief notify core about state changed within a concrete discussion chatWidget
*/
void SslClient::stateChanged(int accid,QString receiverJID,QString state)
{
    qDebug() << "state change requested to " << state;
    this->socket->write(
                        QString("<xml version='1.0'><statechanged><accid>%1</accid><jid>%2</jid><state>%3</state></statechanged>")
                          .arg(accid)
                          .arg(receiverJID)
                          .arg(state)
                          .toUtf8()
                        +"\r\n"
                       );
}
